/*
 * Title:        CloudSim Toolkit
 * Description:  CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation
 *               of Clouds
 * Licence:      GPL - http://www.gnu.org/copyleft/gpl.html
 *
 * Copyright (c) 2009, The University of Melbourne, Australia
 */

package hcmut.edu.vn.examples;

import hcmut.edu.vn.greencloud.Lease;
import hcmut.edu.vn.helps.Helps;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.Datacenter;
import org.cloudbus.cloudsim.DatacenterBroker;
import org.cloudbus.cloudsim.DatacenterCharacteristics;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmAllocationPolicySimple;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.provisioners.PeProvisionerSimple;

/**
 * A simple example showing how to create a datacenter with one host and run two
 * cloudlets on it. The cloudlets run in VMs with the same MIPS requirements.
 * The cloudlets will take the same time to complete the execution.
 */
public class ExampleLease {

	/** The cloudlet list. */
	private static List<Cloudlet> cloudletList;
	//
	// /** The vmlist. */
	private static List<Vm> vmlist;

	private static List<Lease> leaseList = new ArrayList<>();

	/**
	 * Creates main() to run this example
	 */
	public static void main(String[] args) {

		Log.printLine("Starting ExampleLease...");
		try {
			// First step: Initialize the CloudSim package. It should be called
			// before creating any entities.
			int num_user = 1; // number of cloud users
			Calendar calendar = Calendar.getInstance();
			boolean trace_flag = true; // mean trace events

			// Initialize the CloudSim library
			CloudSim.init(num_user, calendar, trace_flag);

			// Second step: Create Datacenters
			// Datacenters are the resource providers in CloudSim. We need at
			// list one of them to run a CloudSim simulation
			Datacenter datacenter0 = createDatacenter("Datacenter_0");

			// Third step: Create Broker
			DatacenterBroker broker = createBroker();
			int brokerId = broker.getId();

			// create lease List
			createLeaseList(brokerId);

			// submit lease list to broker
			broker.submitLeaseList(leaseList);			

			// Sixth step: Starts the simulation
			CloudSim.startSimulation();

			// Final step: Print results when simulation is over
			List<Cloudlet> newList = broker.getCloudletReceivedList();

			CloudSim.stopSimulation();

			printCloudletList(newList);

			// Print the debt of each user to each datacenter
			datacenter0.printDebts();

			Log.printLine("ExampleLease finished!");
		} catch (Exception e) {
			e.printStackTrace();
			Log.printLine("The simulation has been terminated due to an unexpected error");
		}
	}

	private static Datacenter createDatacenter(String name) {

		Helps helps = new Helps();
		// Here are the steps needed to create a PowerDatacenter:
		// 1. We need to create a list to store
		// our machine
		List<Host> hostList = new ArrayList<>();

		// 2. A Machine contains one or more PEs or CPUs/Cores.
		// In this example, it will have only one core.
		List<Pe> peList = new ArrayList<Pe>();

		int mips = 1000;

		// 3. Create PEs and add these into a list.
		peList.add(new Pe(0, new PeProvisionerSimple(mips))); // need to store
																// Pe id and
																// MIPS Rating

		// 4. Create Host with its id and list of PEs and add them to the list
		// of machines
		int hostNumber = 5;
		hostList = helps.createHostList(hostNumber);

		// 5. Create a DatacenterCharacteristics object that stores the
		// properties of a data center: architecture, OS, list of
		// Machines, allocation policy: time- or space-shared, time zone
		// and its price (G$/Pe time unit).
		String arch = "x86"; // system architecture
		String os = "Linux"; // operating system
		String vmm = "Xen";
		double time_zone = 10.0; // time zone this resource located
		double cost = 3.0; // the cost of using processing in this resource
		double costPerMem = 0.05; // the cost of using memory in this resource
		double costPerStorage = 0.001; // the cost of using storage in this
										// resource
		double costPerBw = 0.0; // the cost of using bw in this resource
		LinkedList<Storage> storageList = new LinkedList<Storage>(); // we are
																		// not
																		// adding
																		// SAN
																		// devices
																		// by
																		// now

		DatacenterCharacteristics characteristics = new DatacenterCharacteristics(
				arch, os, vmm, hostList, time_zone, cost, costPerMem,
				costPerStorage, costPerBw);

		// 6. Finally, we need to create a PowerDatacenter object.
		Datacenter datacenter = null;
		try {
			datacenter = new Datacenter(name, characteristics,
					new VmAllocationPolicySimple(hostList), storageList, 0); // ----
																				// use
																				// Best
																				// Fit
																				// Decrease
		} catch (Exception e) {
			e.printStackTrace();
		}

		return datacenter;
	}

	// We strongly encourage users to develop their own broker policies, to
	// submit vms and cloudlets according
	// to the specific rules of the simulated scenario
	private static DatacenterBroker createBroker() {

		DatacenterBroker broker = null;
		try {
			broker = new DatacenterBroker("Broker");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return broker;
	}

	/**
	 * Prints the Cloudlet objects
	 * 
	 * @param list
	 *            list of Cloudlets
	 */
	private static void printCloudletList(List<Cloudlet> list) {
		int size = list.size();
		Helps helps = new Helps();
		list = helps.sortCloudletListBaseETime(list);
		
		Cloudlet cloudlet;

		String indent = "    ";
		Log.printLine();
		Log.printLine("========== OUTPUT ==========");
		Log.printLine("Cloudlet ID" + indent + "STATUS" + indent
				+ "Data center ID" + indent + "VM ID" + indent + "Lease ID"
				+ indent + "Time" + indent + "Start Time" + indent 
				+ "Finish Time");

		DecimalFormat dft = new DecimalFormat("###.##");
		for (int i = 0; i < size; i++) {
			cloudlet = list.get(i);
			Log.print(indent + cloudlet.getCloudletId() + indent + indent);

			if (cloudlet.getCloudletStatus() == Cloudlet.SUCCESS) {
				Log.print("SUCCESS");

				Log.printLine(indent + indent + cloudlet.getResourceId()
						+ indent + indent + indent + cloudlet.getVmId()
						+ indent + indent + indent + cloudlet.getLeaseId()
						+ indent + indent
						+ dft.format(cloudlet.getActualCPUTime()) + indent
						+ indent + dft.format(cloudlet.getExecStartTime())
						+ indent + indent + indent
						+ dft.format(cloudlet.getFinishTime()));
			}
		}

	}

	// ============== HCMUT ====================
	public static void createLeaseList(int brokerId) throws IOException {
		Helps helps = new Helps();

		// create all VM list for all lease
		cloudletList = helps.createCloudletList(brokerId,
				"examples/workload/test/wl_test");

		vmlist = helps.createVmList(brokerId);

		// Create 2 lease
		int leaseId = 0;
		int cloudNumber = 5;
		String hardware = "HCMUT";
		String software = "HCMUT";

		// ================ create lease 1============================
		int indexStart = 0;
		int scope[] = new int[] { indexStart, indexStart + cloudNumber };
		double startTime_L1 = 50;
		double duration_L1 = Integer.MAX_VALUE;
		
		List<Cloudlet> cloudletList_1 = helps.createCloudletListEachLease(
				cloudletList, leaseId, startTime_L1, duration_L1, scope);
		cloudletList_1 = helps.sortCloudletListBaseETime(cloudletList_1);

		List<Vm> vmList_1 = helps.createVmListEachLease(vmlist, leaseId, startTime_L1, scope);

		Lease lease1 = new Lease(leaseId, vmList_1, cloudletList_1, hardware,
				software, -1, startTime_L1, duration_L1, -1, false);
		// ======================================================

		// =============== create Lease 2 ==========================
		leaseId++;
		indexStart += cloudNumber;
		scope = new int[] { indexStart, indexStart + cloudNumber };
		double startTime_L2 = 150;
		double duration_L2 = Integer.MAX_VALUE;

		List<Cloudlet> cloudletList_2 = helps.createCloudletListEachLease(
				cloudletList, leaseId, startTime_L2, duration_L2, scope);
		cloudletList_2 = helps.sortCloudletListBaseETime(cloudletList_2);

		List<Vm> vmList_2 = helps.createVmListEachLease(vmlist, leaseId, startTime_L2, scope);

		Lease lease2 = new Lease(leaseId, vmList_2, cloudletList_2, hardware,
				software, -1, startTime_L2, duration_L2, -1, false);
		// ==========================================================
		leaseList.add(lease1);
		leaseList.add(lease2);

	}
	// ========================== FINISH ===================
}
